package com.saascloud.mybatis.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.saascloud.core.SessionContext;
import com.saascloud.mybatis.core.handler.DefaultFieldHandler;
import com.saascloud.mybatis.core.method.MpExtSqlInjector;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * @Author: liangxu
 * @Contact: one_dream@aliyun.com
 * @Date: 2022/4/25 11:21
 * @Version: 1.0
 * @Description:
 */
@Slf4j
@MapperScan("com.isoftstone.**.mapper")
public class MybatisAutoConfiguration {

    @Autowired
    private Environment environment;

    /**
     * 分页插件
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        /*分页插件*/
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return mybatisPlusInterceptor;
    }

//    @Bean
//    @ConditionalOnProperty(name = "saas.mp.tenantIgnoreTables")
//    public TenantLineInnerInterceptor tenantLineInnerInterceptor() {
//        log.info("初始化mybatis plus 多租户插件");
//        String ignoreTables = environment.getProperty("saas.mp.tenantIgnoreTables");
//        Set<String> ignoreTableSet = new HashSet<>();
//        if (!StringUtils.isEmpty(ignoreTables)) {
//            String[] split = ignoreTables.split(",");
//            ignoreTableSet = new HashSet<String>(Arrays.asList(split));
//        }
//        return new TenantLineInnerInterceptor(new TenantInterceptor(ignoreTableSet));
//    }

    /**
     * mybatis plus 自动填充字段处理
     *
     * @param sessionContext
     * @return
     */
    @Bean
//    @ConditionalOnBean(SessionContext.class)
    public MetaObjectHandler defaultMetaObjectHandler(@Autowired(required = false) SessionContext sessionContext) {
        return new DefaultFieldHandler(sessionContext);
    }

    /**
     * 增加批量插入和更新方法
     *
     * @return
     */
    @Bean
    public MpExtSqlInjector mpExtSqlInjector() {
        return new MpExtSqlInjector();
    }

}
